package br.com.fritadorcorrente.utils;

import java.awt.EventQueue;
import java.io.IOException;
import java.io.OutputStream;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
import javax.swing.text.Style;

public class TextComponentStream extends OutputStream {

    private JTextComponent textComponent;
    private Style error;

    public TextComponentStream(JTextComponent textComponent, Style error) {
        this.textComponent = textComponent;
        this.error = error;
    }

    public void println(String text) {
        print(text + "\n");
    }

    public void print(String text) {
        try {
            write(text.getBytes());
        } catch (IOException e) {
            //Faça o log da exceção aqui
        }
    }

    @Override
    public void write(final int b) throws IOException {
        write(new byte[]{(byte) b}, 0, 1);
    }

    @Override
    public void write(final byte[] b, final int off, final int len)
            throws IOException {
        final String str = new String(b, off, len);

        EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    textComponent.getDocument().insertString(
                            textComponent.getDocument().getLength(), str, error);
                } catch (BadLocationException e) {
                    //Faça o log da exceção aqui
                }
            }
        });
    }

    @Override
    public void flush() {
    }

    @Override
    public void close() {
    }
}